package org.example.juc.taskgroup;

import java.util.concurrent.*;

public class CompletionServiceExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 创建 CompletionService
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);

        // 提交多个任务
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            completionService.submit(() -> {
                // 模拟任务执行
                Thread.sleep(1000); // 模拟耗时操作
                return taskId * 2; // 返回结果
            });
        }

        // 获取结果
        for (int i = 0; i < 5; i++) {
            Future<Integer> future = completionService.take(); // 阻塞直到有任务完成
            System.out.println("Result: " + future.get()); // 获取并打印结果
        }

        // 关闭线程池
        executor.shutdown();
    }
}